﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Web;
using CSF.JobNotifier.BLL;
using CSF.JobNotifier.Data;
using RB.Web.Security;

namespace CSF.JobNotifier.Service
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“JobNotifyService”。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class JobNotifyService : IJobNotifyService
    {

        public WorkProcessMessage[] GetWorkProcess(string ticket)
        {
            HttpContext context = HttpContext.Current;
            bool auth = VarAuthentication.Authenticate(context, ticket);
            if (auth)
            {
                WorkProcessSet wpSet = new WorkProcessSet();
                List<WorkProcess> list = wpSet.AsQueryable().ToList();
                WorkProcessMessage[] mess = new WorkProcessMessage[list.Count];
                int i = 0;
                foreach (WorkProcess item in list)
                {
                    mess[i] = new WorkProcessMessage();
                    mess[i].Code = item.Code;
                    mess[i].Id = item.Id;
                    mess[i].Name = item.Name1;
                    mess[i].Color = item.Color;
                    i++;
                }
                return mess;
            }
            return null;
        }

        public JobNotifyMessage GetNextJob(string ticket, int no)
        {
            HttpContext context = HttpContext.Current;
            bool auth = VarAuthentication.Authenticate(context, ticket);
            if (auth)
            {
                VarIdentity identity = (VarIdentity)context.User.Identity;
                Guid userId = identity.UserId;

                JobNotifyMessage model = new JobNotifyMessage();
                JobSet jobSet = new JobSet();
                //全部未完成的job
                model.TotalJobCount = jobSet.Count();
                //当前用户名下未完成的job数
                WorkProcessUserSet wpuSet = new WorkProcessUserSet();
                JobProcessLogSet jplSet = new JobProcessLogSet();
                var query = from t1 in jplSet
                            join t2 in wpuSet on t1.WorkProcessId equals t2.WorkProcessId
                            where t2.UserId == userId
                            select t1.JobNo;
                var list = query.ToList();
                model.MyJobCount = model.TotalJobCount - list.Count;

                var myjobs = jobSet.Select(p => p.JobNo).ToList().Except(list);
                //去第no个
                model.JobNo = myjobs.Skip(no).Take(1).FirstOrDefault();
                //当前JobNo完成步骤
                model.FinishedProcessId = (from t1 in jplSet
                                           where t1.JobNo == model.JobNo
                                           select t1.WorkProcessId).ToArray();
                var job = jobSet.AsQueryable().Where(p => p.JobNo == model.JobNo).FirstOrDefault();
                model.ItemCode = job.ItemCode;
                model.ItemQty = job.ItemQty;
                return model;
            }
            return null;
        }

        public JobMessage[] GetProcessingJobs(string ticket, bool all)
        {
            throw new NotImplementedException();
        }

        public int SetProcessJob(string ticket, string jobNo,string itemCode,string qulity,string gP1,bool isUrgent,string comment)
        {
            //-1代表保存失败,1代表保存成功,0代表权限不够
            HttpContext context = HttpContext.Current;
            bool auth = VarAuthentication.Authenticate(context, ticket);
            if (auth)
            {
                VarIdentity identity = (VarIdentity)context.User.Identity;
                Guid userId = identity.UserId;


                //判断jobNo是否存在,如果不存在,则加入到job表里,存在则更新
                JobSet jobSet = new JobSet();
                var jobIsExist = jobSet.AsQueryable().Where(p => p.JobNo == jobNo).Count();

                WorkProcessUserSet wpuSet = new WorkProcessUserSet();
                var query = wpuSet.AsQueryable().Where(p => p.UserId == userId).Select(p => p.WorkProcessId).FirstOrDefault();
                //不存在
                if (jobIsExist == 0)
                {
                    //第一次只是增加jobno到job表中,只有第一个人有权限增加jobno
                    
                    //1表示第1道工序的人
                    if (query == 1)
                    {
                        jobSet.Add(new Job() { JobNo = jobNo,CreateTime=DateTime.Now,CreateBy=userId.ToString(),GP1=gP1,IsUrgent=isUrgent});
                        //然后再加入到已完成里面
                        AddNewWorkProcess(userId, jobNo);
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                }
                //存在
                else
                {
                    //jobNo存在,且工序为2
                    if (query == 2)
                    {
                        var jobModle = jobSet.AsQueryable().Where(p => p.JobNo == jobNo).FirstOrDefault();
                        jobModle.ItemCode = itemCode;
                        if (!string.IsNullOrEmpty(qulity))
                        {
                            jobModle.ItemQty = Convert.ToInt32(qulity);
                        }
                        jobSet[jobNo] = jobModle;
                    }

                    try
                    {
                        AddNewWorkProcess(userId, jobNo);
                        return 1;
                    }
                    catch
                    {
                        return -1;
                    }
                }
            }
            return 0;
        }

        public void FinishByJonNo(string jobNo)
        {
            JobProcessLogSet jplSet = new JobProcessLogSet();
            var query = jplSet.AsQueryable().Where(p => p.JobNo == jobNo).Select(p => p.WorkProcessId).Count();
            if (query >= 5)
            {
                jplSet.RemoveAll(p => p.JobNo == jobNo);
                FinishedJobSet finishJobSet = new FinishedJobSet();
                finishJobSet.Add(new FinishedJob() { JobNo = jobNo, CreateTime = DateTime.Now });
            }
        }

        public List<NotFinishJobMessage> GetAllNotFinishMessage()
        {

            JobSet jobSet = new JobSet();
            List<Job> jobList = jobSet.AsQueryable().OrderBy(p => p.JobNo).ToList();
            return GetDetails(jobList);
        }

        public List<NotFinishJobMessage> GetNotFinishByUser(string ticket)
        {
            HttpContext context = HttpContext.Current;
            bool auth = VarAuthentication.Authenticate(context, ticket);
            VarIdentity identity = (VarIdentity)context.User.Identity;
            Guid userId = identity.UserId;

            //当前用户名下未完成的job数
            WorkProcessUserSet wpuSet = new WorkProcessUserSet();
            var workProcessId = wpuSet.AsQueryable().Where(p => p.UserId == userId).Select(p => p.WorkProcessId).FirstOrDefault();
            JobProcessLogSet jplSet = new JobProcessLogSet();
            var jobNos = jplSet.AsQueryable().Where(p => p.WorkProcessId == workProcessId).Select(p => p.JobNo).ToList();
            JobSet jobSet = new JobSet();
            IQueryable<Job> query = null;
            if (jobNos.Count != 0)
            {
                query = from p in jobSet
                        where !jobNos.Contains(p.JobNo)
                        select p;
            }
            else
            {
                query = from p in jobSet
                        select p;
            }
         
            return GetDetails(query.ToList());

        }

        private List<NotFinishJobMessage> GetDetails(List<Job> jobs)
        {
           
            List<NotFinishJobMessage> list = new List<NotFinishJobMessage>();
            foreach (Job job in jobs)
            {
                StringBuilder sb = new StringBuilder("");
                NotFinishJobMessage model = new NotFinishJobMessage();
                model.JobNo = job.JobNo;

                JobProcessLogSet jplSet = new JobProcessLogSet();

                var query = jplSet.AsQueryable().Where(p => p.JobNo == job.JobNo && p.WorkProcessId == 1).FirstOrDefault();
                if (query == null)
                    model.Step1 = "N";
                else
                {
                    model.Step1 = "Y";
                    sb.Append(query.Comment);
                }
                query = jplSet.AsQueryable().Where(p => p.JobNo == job.JobNo && p.WorkProcessId == 2).FirstOrDefault();
                if (query == null)
                    model.Step2 = "N";
                else
                {
                    model.Step2 = "Y";
                    sb.Append(query.Comment);
                }
                query = jplSet.AsQueryable().Where(p => p.JobNo == job.JobNo && p.WorkProcessId == 3).FirstOrDefault();
                if (query == null)
                    model.Step3 = "N";
                else
                {
                    model.Step3 = "Y";
                    sb.Append(query.Comment);
                }
                query = jplSet.AsQueryable().Where(p => p.JobNo == job.JobNo && p.WorkProcessId == 4).FirstOrDefault();
                if (query == null)
                    model.Step4 = "N";
                else
                {
                    model.Step4 = "Y";
                    sb.Append(query.Comment);
                }
                query = jplSet.AsQueryable().Where(p => p.JobNo == job.JobNo && p.WorkProcessId == 5).FirstOrDefault();
                if (query == null)
                    model.Step5 = "N";
                else
                {
                    model.Step5 = "Y";
                    sb.Append(query.Comment);
                }
                model.ItemCode = job.ItemCode;
                model.Quanlity = job.ItemQty;
                model.Comment = sb.ToString();
                model.GP1 = job.GP1;
                model.IsUrgent = job.IsUrgent;
                list.Add(model);
            }
            return list;
        }

        private void AddNewWorkProcess(Guid userId, string jobNo)
        {
            JobProcessLogSet jplSet = new JobProcessLogSet();
            JobProcessLog model = new JobProcessLog();
            model.JobNo = jobNo;
            WorkProcessUserSet wpuSet = new WorkProcessUserSet();
            model.WorkProcessId = (from t1 in wpuSet
                                   where t1.UserId == userId
                                   select t1.WorkProcessId).FirstOrDefault();
            model.ProcessTime = DateTime.Now;
            model.ProcessBy = userId.ToString();
            jplSet.Add(model);
        }
    }
}